#!/bin/bash

# download linux kernel
# wget https://www.kernel.org/pub/linux/kernel/v6.x/linux-6.17.7.tar.xz

build linux kernel
rm -rf linux-6.17.7
rm -f Image
tar -xf linux-6.17.7.tar.xz
cd linux-6.17.7
    make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- defconfig
    # Enable kernel debugging options
    ./scripts/config --enable CONFIG_DEBUG_INFO
    ./scripts/config --enable CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT
    ./scripts/config --enable CONFIG_GDB_SCRIPTS
    ./scripts/config --disable CONFIG_DEBUG_INFO_REDUCED
    ./scripts/config --set-val CONFIG_FRAME_POINTER y
    make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- olddefconfig
    make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- -j$(nproc)
cd ..

cp linux-6.17.7/arch/arm64/boot/Image .


# download busybox
# wget https://busybox.net/downloads/busybox-1.37.0.tar.bz2

# build busybox
rm -rf busybox-1.37.0
tar -xf busybox-1.37.0.tar.bz2
cd busybox-1.37.0
    make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- defconfig
    sed  's/^.*CONFIG_STATIC[^_].*$/CONFIG_STATIC=y/g' -i .config
    make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- -j$(nproc) busybox
cd ..


# initrd
rm -rf initrd*
mkdir initrd
cd initrd
    mkdir -p bin dev proc sys 
    cd bin
        cp ../../busybox-1.37.0/busybox ./
        for proc in $(./busybox --list); do
            ln -s /bin/busybox ./$proc
        done
    cd ..
    echo '#!/bin/sh' > init
    echo 'mount -t proc proc /proc' >> init
    echo 'mount -t sysfs sysfs /sys' >> init
    echo 'mount -t devtmpfs udev /dev' >> init
    echo 'sysctl -w kernel.printk="2 4 1 7"' >> init
    echo '/bin/sh' >> init
    echo '/bin/poweroff -f' >> init
    chmod +x init
    find . | cpio -o -H newc > ../initrd.img
cd ..

echo "Build completed successfully!"
echo ""
echo "To run with QEMU (no debugging):"
echo "  qemu-system-aarch64 -M virt -cpu cortex-a57 -kernel Image -initrd initrd.img -nographic -append \"console=ttyAMA0 nokaslr\""
echo ""
echo "To run with GDB debugging:"
echo "  1. Start QEMU in one terminal:"
echo "     qemu-system-aarch64 -M virt -cpu cortex-a57 -kernel Image -initrd initrd.img -nographic -append \"console=ttyAMA0 nokaslr\" -s -S"
echo "  2. In another terminal, run:"
echo "     gdb-multiarch linux-6.17.7/vmlinux"
echo "     (gdb) target remote :1234"
echo "     (gdb) break start_kernel"
echo "     (gdb) continue"
echo ""
echo "Or use VS Code tasks: 'Start QEMU' task, then press F5 to debug"



